import { Request, Response, NextFunction } from "express";
import { connection } from "@/services/database";
import { generateUpdateFields, checkIsStudentBelongUser, checkIsAdmin } from "@/utils/sql";

interface Params {
	user_id: number;
	real_name?: string;
	gender?: "male" | "female";
	birth_date?: string;
	identification_number?: string;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const callerId = response.locals.user.id;
		const params = request.body as unknown as Params;
		if (callerId != params.user_id && !(await checkIsStudentBelongUser(callerId, params.user_id)) && !(await checkIsAdmin(callerId))) throw new Error("无权操作");
		(await connection.execute(
			"UPDATE student SET " +
				generateUpdateFields({
					real_name: params.real_name,
					gender: params.gender,
					birth_date: params.birth_date,
					identification_number: params.identification_number,
				}) +
				" WHERE user_id = :user_id",
			params
		)) as any;
		response.json({ data: null, message: "成功" });
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
